#include <assert.h>
#include "channel_map.h"

// msize 是 entrie 项的大小
int map_make_space(struct channel_map *map, int slot, int msize)
{
    if (map->nentries <= slot)
    {
        int nentries = map->nentries ? map->nentries : 32; // 默认 32
        void **tmp;

        while (nentries <= slot) // 如果小于槽数，扩大 2 倍
            nentries <<= 1;

        // 重新开辟内存
        tmp = (void **)realloc(map->entries, nentries * msize);
        if (tmp == NULL)
            return (-1);
        // 前面已分配的不变，后面的全部置 0
        memset(&tmp[map->nentries], 0,
               (nentries - map->nentries) * msize);

        map->nentries = nentries;
        map->entries = tmp;
    }

    return (0);
}

void map_init(struct channel_map *map)
{
    map->nentries = 0; // 暂时 0 个
    map->entries = NULL;
}

void map_clear(struct channel_map *map)
{
    if (map->entries != NULL)
    {
        int i;
        for (i = 0; i < map->nentries; ++i)
        {
            if (map->entries[i] != NULL)
                free(map->entries[i]); // 先 free 掉 entrie
        }
        free(map->entries); // 然后释放 entries
        map->entries = NULL;
    }
    map->nentries = 0;
}
